package cn.xbtop.blog.utils;

import lombok.Data;

import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 分页对象
 *
 * @author Mxb
 * @version 1.0
 * @date 2020/4/13 11:59
 */
@Data
public class PageBean<T> implements Serializable {
    // 定义排序规则
    private static final String ASC = "asc";
    private static final String DESC = "desc";
    //当前页
    private Integer pageNumber = 1;
    //每页条数
    private Integer pageSize = 10;
    //总页数
    private Integer totalPage = 0;
    //总条数
    private Integer totalCount = 0;

    //起始位置
    //private Integer index;

    //数据
    private List<T> list;
    //条件参数
    private Map<String, Object> params = new HashMap<>(16);
    //排序列
    private String sortColumn;
    //排序方式
    private String sortMethods = "asc";

    /**
     * 获取当前页
     * @return
     */
    public Integer getPageNumber() {
        if (pageNumber < 1) {
            return 1;
        }
        return this.pageNumber;
    }

    /**
     * 获取index 起始位置
     *
     * @return
     */
    public Integer getIndex() {
        return (pageNumber - 1) * pageSize;
    }

    /**
     * 设置总条数时  计算总页数
     */
    public void setTotalPage(Integer totalCount) {
        this.totalCount = totalCount;

        this.totalPage = (int) Math.ceil(totalCount * 1.0 / pageSize);
    }

    /**
     * 设置排序方式
     */
    public void setSortMethods(String sortMethods) {
        if (StringUtils.isBlank(sortMethods)) {
           this.sortColumn = "asc";
        }
        //不为空
        if (sortMethods.toLowerCase().startsWith(ASC)) {
            this.sortMethods = ASC;
        } else if (sortMethods.toLowerCase().startsWith(DESC)) {
            this.sortMethods = DESC;
        } else {
            this.sortMethods = ASC;
        }
    }

    /**
     * 设置排序列
     * 驼峰转下滑线
     * @param sortColumn
     */
    public void setSortColumn(String sortColumn){
        this.sortColumn = StringUtils.upperCharToUnderLine(sortColumn);
    }

}
